package org.basis.algorithm.sort;

import org.basis.algorithm.common.SortUtil;

/**
 * 归并排序
 *
 * @author Mr_wenpan@163.com 2021/12/03 10:04
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] arr = {3, 5, 6, 1, 2, 9, 0, 11, 45, 22, 12, 1, 9, 8};
        process(arr);
        SortUtil.printArr(arr);

        final int testCount = 1000000;
        // 对数器对数testCount次，校验算法的正确性
        for (int i = 0; i < testCount; i++) {
            int[] array = SortUtil.generateRandomArray(100, 100);
            process(array);
            int[] array1 = SortUtil.copyArray(array);
            SortUtil.comparator(array1);
            boolean equal = SortUtil.isEqual(array1, array);
            if (!equal) {
                System.out.println("归并排序算法有问题!");
            }
        }
    }

    private static void process(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        doProcess(arr, 0, arr.length - 1);
    }

    private static void doProcess(int[] arr, int left, int right) {
        // base case
        if (left >= right) {
            return;
        }
        int mid = left + (right - left) / 2;
        // 左区间
        doProcess(arr, left, mid);
        // 右区间
        doProcess(arr, mid + 1, right);
        // 归并
        merge(arr, left, mid, right);
    }

    /**
     * 合并左右区间，使得左右区间有序，注意：二分法时，二分区间一般是写成[0,mid] [m+1,n]，如果写成 [0,mid) [m,n] 是不对的，特别注意
     */
    private static void merge(int[] arr, int left, int mid, int right) {
        // 辅助数组
        int[] help = new int[right - left + 1];
        int p1 = left;
        int p2 = mid + 1;
        int i = 0;
        while (p1 <= mid && p2 <= right) {
            // 左右相等也拷贝左边
            if (arr[p1] <= arr[p2]) {
                help[i] = arr[p1];
                p1++;
                i++;
            } else {
                help[i] = arr[p2];
                p2++;
                i++;
            }
        }

        // 谁先越界就拷贝另一个
        while (p2 <= right) {
            help[i++] = arr[p2++];
        }

        while (p1 <= mid) {
            help[i++] = arr[p1++];
        }

        // help已经有序，将help拷贝回原数组
        for (int j = 0; j < help.length; j++) {
            arr[left + j] = help[j];
        }
    }
}
